#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/usb_serial_jtag.h"
#include "sdkconfig.h"
#include "esp_log.h"
#include "esp_check.h"

#define BUF_SIZE (1024)
#define ECHO_TASK_STACK_SIZE (4096)

static void echo_task(void *arg)
{
    // Configure USB SERIAL JTAG
    usb_serial_jtag_driver_config_t usb_serial_jtag_config = {
        .rx_buffer_size = BUF_SIZE,
        .tx_buffer_size = BUF_SIZE,
    };

    ESP_ERROR_CHECK(usb_serial_jtag_driver_install(&usb_serial_jtag_config));
    ESP_LOGI("usb_serial_jtag echo", "USB_SERIAL_JTAG init done");

    // Configure a temporary buffer for the incoming data
    uint8_t *data = (uint8_t *) malloc(BUF_SIZE);
    if (data == NULL) {
        ESP_LOGE("usb_serial_jtag echo", "no memory for data");
        return;
    }

    while (1) {
        // 读取USB串口数据
        int len = usb_serial_jtag_read_bytes(data, (BUF_SIZE - 1), 20 / portTICK_PERIOD_MS);
        // 根据长度判断接下来该怎么办
        if (len) {
            if(len == 4){
                uint8_t head = data[0];
                uint8_t cmd = data[1];
                uint8_t check = data[2];
                uint8_t tail = data[3];
                if(head == 0x7b && tail == 0x7a && check == 0x00){
                    switch(cmd){
                        case 0x01: // 打开加热头
                            printf("open hot\n");
                            break;
                        case 0x02: // 关闭加热头
                            printf("close\n");
                            break;
                        case 0x03: // 让纸张走几步
                            printf("move step\n");
                            break;
                    }
                }
            }else if (len > 4){
                printf("print data\n");
            }
        }else{
             vTaskDelay(pdMS_TO_TICKS(10)); 
        }
    }
}

void example_usb_serial_app_main(void)
{
    xTaskCreate(echo_task, "USB SERIAL JTAG_echo_task", ECHO_TASK_STACK_SIZE, NULL, 10, NULL);
}